package cn.fancy.sdk.login;

import static cn.fancy.sdk.utils.SpMmkvUtils.KEY_VERTICAL_ORIENTATION;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import cn.fancy.sdk.FancyManager;
import cn.fancy.sdk.baseview.BaseView;
import cn.fancy.sdk.baseview.IActivityManager;
import cn.fancy.sdk.common.utils.Logger;
import cn.fancy.sdk.common.utils.NetworkImpl;
import cn.fancy.sdk.common.utils.ResUtil;
import cn.fancy.sdk.common.utils.ResourceUtil;
import cn.fancy.sdk.common.utils.SdkAsyncTask;
import cn.fancy.sdk.entity.GuildBaseInfo;
import cn.fancy.sdk.entity.Session;
import cn.fancy.sdk.login.view.LoginView;
import cn.fancy.sdk.utils.CommMessage;
import cn.fancy.sdk.utils.SpMmkvUtils;
import java.util.Stack;

/**
 * Created by zhaojh on date 2020/10/30
 */
public class LoginViewActivity extends Activity implements OnClickListener, IActivityManager {
    private static final String TAG = LoginViewActivity.class.getSimpleName();
    
    private Activity mActivity;
    
    /* LoginActivity迁移过来 */
    private Stack<BaseView> vStack = new Stack<>();
    private ScrollView.LayoutParams ScrollViewLayoutParams = new ScrollView.LayoutParams(
        ScrollView.LayoutParams.MATCH_PARENT, ScrollView.LayoutParams.MATCH_PARENT);
    private ScrollView content;
    private LinearLayout titleBar;
    private Dialog waitingDialog = null;
    private LayoutInflater inflater;
    private TextView titleDes;
    private LinearLayout titleSteps;
    private SdkAsyncTask<String> initAsyncTask;
    private TextView startDisplayTv;
    private Button startConfirmBtn;
    private ImageView rotate_anim_img = null;
    private RotateAnimation rotate_anim = null;
    
    public static void start(Context context, QdLoginCallback qdLoginCallback) {
        Intent intent = new Intent(context, LoginViewActivity.class);
        context.startActivity(intent);
        CommMessage.sLoginCallback = qdLoginCallback;
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = this;
        
        if(SpMmkvUtils.getValue(this, KEY_VERTICAL_ORIENTATION).equals(KEY_VERTICAL_ORIENTATION)){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            Log.w(TAG, TAG + "setRequestedOrientation PORTRAIT");
        }
        inflater = LayoutInflater.from(this);
        // 跳过初始化，直接显示登录界面进行账号更换
        if (CommMessage.isChangingAccount) {
            setContentView(ResUtil.getLayoutId(mActivity, "guild_login_activity"));
            initView();
            pushViewToStack(new LoginView(mActivity, this));
            return;
        }
        // 清理可能静态保存的Session数据
        Session.clear(mActivity);
        setContentView(ResUtil.getLayoutId(mActivity, "guild_start_view"));
        startDisplayTv = (TextView) this.findViewById(ResUtil.getId(mActivity,
            "guild_start_display_tv"));
        TextView startHotlineTv = (TextView) this.findViewById(ResUtil.getId(mActivity,
            "guild_start_hotline_tv"));
        TextView startQQTv = (TextView) this.findViewById(ResUtil.getId(mActivity,
            "guild_start_qq_tv"));
        startConfirmBtn = (Button) this.findViewById(ResUtil.getId(mActivity,
            "guild_start_confirm_btn"));
        startConfirmBtn.setOnClickListener(this);
        rotate_anim_img = (ImageView) this.findViewById(ResUtil.getId(mActivity,
            "guild_start_img_rotate"));
        GuildBaseInfo.isGuildLogin = false;
        
        String phone = "";
        startHotlineTv.setText(phone);
        String qq = "";
        startQQTv.setText(qq);
        setContentView(ResUtil.getLayoutId(mActivity, "guild_login_activity"));
        initView();
        pushViewToStack(new LoginView(mActivity, this));
    }
    
    @Override
    public void onClick(View v) {
        if (v.getId() == ResUtil.getId(mActivity, "guild_back")) {
            onBackPressed();
        } else if (v.getId() == ResUtil.getId(mActivity, "guild_start_confirm_btn")) {
            this.init();
        }
    }
    
    private RotateAnimation getRotateAnim() {
        if (rotate_anim == null) {
            rotate_anim = new RotateAnimation(0, 360,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
            rotate_anim.setDuration(1500);
            rotate_anim.setRepeatMode(1);
            rotate_anim.setRepeatCount(-1);
            rotate_anim.setInterpolator(new LinearInterpolator());
        }
        return rotate_anim;
    }
    
    private void notifyLoginQuit() {
        if (CommMessage.sLoginCallback != null) {
            CommMessage.sLoginCallback.callback(QdLoginCallback.USER_QUIT,
                QdLoginCallback.USER_QUIT_DES, null);
        } else {
            Logger.print_red("logincallback is null");
        }
        finish();
        Logger.print_red("LoginActivity Finished");
    }
    
    public void notifyLoginSuccess(QdLoginResult loginResult) {
        GuildBaseInfo.isGuildLogin = true;
        if (CommMessage.sLoginCallback != null) {
            CommMessage.sLoginCallback.callback(QdLoginCallback.SUCCEEDED,
                QdLoginCallback.SUCCEEDED_DES, loginResult);
            CommMessage.havedlogin = true;
            ShowToastMsg toast = new ShowToastMsg();
            toast.show(this, loginResult.userName + ", 登录成功 ~ ");
            // 开启浮标
            if (SpMmkvUtils.getValue(this, SpMmkvUtils.KEY_FLOAT_DISPLAY) != null && SpMmkvUtils.getValue(this, SpMmkvUtils.KEY_FLOAT_DISPLAY).equals("1")) {
                FancyManager.getInstance().showFloat(mActivity);
            }
        } else {
            Log.e("notify Login", "login callback is null");
        }
    }
    
    @Override
    public void setMessBind(boolean isGo) {
    
    }
    
    @Override
    public void showMenuItems(int showing, int stepnumber) {
    
    }
    
    public static void staticnotifyLoginSuccess(QdLoginResult loginResult,
        Context context) {
        GuildBaseInfo.isGuildLogin = true;
        if (CommMessage.sLoginCallback != null) {
            CommMessage.sLoginCallback.callback(QdLoginCallback.SUCCEEDED,
                QdLoginCallback.SUCCEEDED_DES, loginResult);
            CommMessage.havedlogin = true;
            ShowToastMsg toast = new ShowToastMsg();
            toast.show(context, loginResult.userName + ", 登录成功 ~ ");
            // 开启浮标
            if (SpMmkvUtils.getValue(context, SpMmkvUtils.KEY_FLOAT_DISPLAY) != null &&
                SpMmkvUtils.getValue(context, SpMmkvUtils.KEY_FLOAT_DISPLAY).equals("1")) {
                FancyManager.getInstance().showFloat(context);
            }
        } else {
            Log.e("notify Login", "login callback is null");
        }
    }
    
    private void init() {
        startConfirmBtn.setVisibility(View.GONE);
        startDisplayTv.setVisibility(View.GONE);
        rotate_anim_img.setVisibility(View.VISIBLE);
        rotate_anim_img.startAnimation(getRotateAnim());
        
        if (!NetworkImpl.isNetworkConnected(mActivity)) {
            rotate_anim_img.clearAnimation();
            rotate_anim_img.setVisibility(View.GONE);
            startDisplayTv.setText(ResourceUtil.getStringFromRes(mActivity,
                ResUtil.getStringId(mActivity,
                    "guild_sdk_init_local_network_error")));
            startDisplayTv.setVisibility(View.VISIBLE);
            startConfirmBtn.setVisibility(View.VISIBLE);
        } else {
            initAsyncTask = new SdkAsyncTask<String>() {
                @Override
                protected String doInBackground() {
                    return "";
                }
                
                @Override
                protected void onCancelled() {
                }
                
                @Override
                protected void onPostExecute(String rst) {
                    rotate_anim_img.clearAnimation();
                    rotate_anim_img.setVisibility(View.GONE);
                    if (rst != null) {
                        // SDK初始化成功，或者SDK已经初始化，展现登录主界面
                        if (rst.equals("ok")) {
                            setContentView(ResUtil.getLayoutId(mActivity,
                                "guild_login_activity"));
                            initView();
                            pushViewToStack(new LoginView(mActivity, LoginViewActivity.this));
                        }
                    } else {
                        startDisplayTv
                            .setText(ResourceUtil.getStringFromRes(
                                mActivity,
                                ResUtil.getStringId(mActivity,
                                    "guild_sdk_init_network_server_error")));
                    }
                    startConfirmBtn.setVisibility(View.VISIBLE);
                    startDisplayTv.setVisibility(View.VISIBLE);
                }
                
                @Override
                public Activity getOwnerActivity() {
                    return (Activity) mActivity;
                }
                
            };
            
            startDisplayTv.setText(ResourceUtil.getStringFromRes(mActivity,
                ResUtil.getStringId(mActivity, "guild_sdk_init")));
            initAsyncTask.execute();
        }
    }
    
    private void initView() {
        titleBar = (LinearLayout) this.findViewById(ResUtil.getId(mActivity,
            "guild_title_bar"));
        ImageView backBt = (ImageView) this.findViewById(ResUtil.getId(mActivity,
            "guild_back"));
        backBt.setOnClickListener(this);
        titleDes = (TextView) this.findViewById(ResUtil.getId(mActivity,
            "guild_title_desc"));
        titleSteps = (LinearLayout) this.findViewById(ResUtil.getId(mActivity,
            "guild_title_steps"));
        content = (ScrollView) this.findViewById(ResUtil.getId(mActivity,
            "guild_login_content"));
    }
    
    
    private void updateContent(final View cv) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                content.setVisibility(View.VISIBLE);
                content.removeAllViews();
                content.addView(cv, ScrollViewLayoutParams);
            }
        });
    }
    
    public void onBackPressed() {
        if (CommMessage.sifLoginViewNow) {
            finish();
            return;
        }
        if (CommMessage.sifRealReturnLoginView) {
            popViewFromStack();
            popViewFromStack();
            CommMessage.sifRealReturnLoginView = false;
            return;
        }
        if (CommMessage.sifReturnLoginView) {
            popViewFromStack();
            pushViewToStack(new LoginView(mActivity, this));
            return;
        }
        synchronized (this) {
            BaseView curView = vStack.peek();
            if (curView.viewId != null) {
                vStack.clear();
            }
            popViewFromStack();
            if (vStack.size() > 0) {
                updateContent(vStack.peek());
            } else {
                if (rotate_anim_img != null) {
                    rotate_anim_img.clearAnimation();
                }
                notifyLoginQuit();
            }
        }
    }
    
    @Override
    public void showWaitingDialog() {
        cancelWaitingDialog();
        
        View dialogView = inflater.inflate(
            ResUtil.getLayoutId(mActivity, "guild_waiting_dialog"), null);
        
        LinearLayout dialogLayout = (LinearLayout) dialogView
            .findViewById(ResUtil.getId(mActivity,
                "guild_waiting_dialog_layout"));
        
        ImageView iv = (ImageView) dialogView.findViewById(ResUtil.getId(
            mActivity, "guild_waiting_img"));
        iv.startAnimation(AnimationUtils.loadAnimation(mActivity,
            ResUtil.getAnimId(mActivity, "guild_waiting_anim")));
        
        waitingDialog = new Dialog(mActivity, ResUtil.getStyleId(mActivity,
            "guild_waiting_dialog"));
        
        waitingDialog.setCanceledOnTouchOutside(false);
        
        waitingDialog.setContentView(dialogLayout,
            new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));
        
        waitingDialog.setCancelable(true);
        waitingDialog.setOnCancelListener(new OnCancelListener() {
            
            @Override
            public void onCancel(DialogInterface dialog) {
                if (vStack.size() > 0) {
                    vStack.peek().stopSyncTask(true);
                }
            }
        });
        waitingDialog.show();
    }
    
    @Override
    public void cancelWaitingDialog() {
        try {
            if (waitingDialog != null && waitingDialog.isShowing()) {
                /* 不继续call onCancelledListener回调 */
                waitingDialog.dismiss();
            }
            waitingDialog = null;
        } catch (IllegalArgumentException e) {
            waitingDialog = null;
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void showToastMsg(final String msg) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    public void pushViewToStack(BaseView v) {
        vStack.push(v);
        updateContent(v);
    }
    
    public void popViewFromStack() {
        if (vStack.size() > 0) {
            vStack.pop();
            Log.e("popViewFromStack", "popViewFromStack");
        }
    }
    
    @Override
    public void popViewFromStackWithUpdatedContent() {
    
    }
    
    @Override
    public void showTitleBar(boolean showing) {
        if (showing) {
            if (titleBar != null) {
                titleBar.setVisibility(View.VISIBLE);
            }
        } else {
            if (titleBar != null) {
                titleBar.setVisibility(View.GONE);
            }
        }
    }
    
    @Override
    public void showLogoBar(int showing) {
    
    }
    
    @Override
    public void setTitleDesc(int showing, String title) {
        titleDes.setVisibility(showing);
        
        if (title != null) {
            titleDes.setText(title);
        }
    }
    
    @Override
    public void showTitleSteps(int showing, int stepnumber) {
        titleSteps.setVisibility(showing);
    }
    
    @Override
    public void setTitleStep1Content(String content) {
    
    }
    
    @Override
    public void setTitleStep2Content(String content) {
    
    }
    
    @Override
    public void NewpopViewFromStack() {
        popViewFromStack();
    }
    
    @Override
    public void finishDialogOrActivity() {
        finish();
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        if (this.initAsyncTask != null) {
            this.initAsyncTask.cancel(true);
        }
    }
}
